<template xlang="wxml">
    <view class="tki-tree-view">
        <scroll-view class="tki-tree-view-sc" :scroll-y="true">
            <block v-for="(item, index) in treeList" :key="index">
                <view
                    class="tki-tree-item"
                    :style="[
                        {
                            paddingLeft: item.rank * 15 + 'px',
                            zIndex: item.rank * -1 + 50,
                        },
                    ]"
                    :class="{
                        border: border === true,
                        show: item.show,
                        last: item.lastRank,
                        showchild: item.showChild,
                        open: item.open,
                    }"
                >
                    <view
                        class="tki-tree-label"
                        :class="item.labelLevel === 3?'tki_tree_label':''"
                        @click.stop="_treeItemTap(item, index)"
                    >
					<u-icon :name="item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon"
							style="margin-right:5rpx"></u-icon>
                        {{ item.labelName }}
                    </view>
					<view @click.stop="_treeItemSelect(item, index)">
                        <u-button class="subscribe_btn" :text="item.subscribe ? '已关注' : '关注'" size="mini" type="primary" :plain="!item.subscribe"></u-button>
					</view>
                </view>
            </block>
        </scroll-view>
    </view>
</template>

<script>
export default {
    name: "tree",
    props: {
        range: {
            type: Array,
            default: function () {
                return [];
            },
        },
        idKey: {
            type: String,
            default: "id",
        },
        rangeKey: {
            type: String,
            default: "label",
        },
        title: {
            type: String,
            default: "",
        },
        multiple: {
            // 是否可以多选
            type: Boolean,
            default: false,
            // default: true
        },
        selectParent: {
            //是否可以选父级
            type: Boolean,
            default: false,
        },
        foldAll: {
            //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
            type: Boolean,
            default: false,
        },
        confirmColor: {
            // 确定按钮颜色
            type: String,
            default: "", // #07bb07
        },
        cancelColor: {
            // 取消按钮颜色
            type: String,
            default: "", // #757575
        },
        titleColor: {
            // 标题颜色
            type: String,
            default: "", // #757575
        },
        currentIcon: {
				type: String,
				default: 'arrow-down'
			},
			defaultIcon: {
				type: String,
				default: 'arrow-right'
			},
			lastIcon: {
				type: String,
				default: ''
			},
        border: {
            // 是否有分割线
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            showTree: true,
            treeList: [],
            selectIndex: -1,
        };
    },
    computed: {},
    methods: {
        //扁平化树结构
        _renderTreeList(list = [], rank = 0, parentId = [], parents = []) {
            list.forEach((item) => {
                this.treeList.push({
                    id: item[this.idKey],
                    name: item[this.rangeKey],
					labelName: item.labelName,
					labelLevel: item.labelLevel,
					subscribe: item.subscribe,
                    source: item,
                    parentId, // 父级id数组
                    parents, // 父级id数组
                    rank, // 层级
                    showChild: false, //子级是否显示
                    open: false, //是否打开
                    show: rank === 0, // 自身是否显示
                    hideArr: [],
                    orChecked: item.checked ? item.checked : false,
                    checked: item.checked ? item.checked : false,
                });
                if (Array.isArray(item.children) && item.children.length > 0) {
                    // console.log(item)
                    let parentid = [...parentId],
                        parentArr = [...parents],
                        childrenid = [...childrenid];
                    delete parentArr.children;
                    parentid.push(item[this.idKey]);
                    parentArr.push({
                        [this.idKey]: item[this.idKey],
                        [this.rangeKey]: item[this.rangeKey],
                    });
                    this._renderTreeList(
                        item.children,
                        rank + 1,
                        parentid,
                        parentArr
                    );
                } else {
                    this.treeList[this.treeList.length - 1].lastRank = true;
                }
            });
            // console.log(list)
        },
        // 处理默认选择
        _defaultSelect() {
            this.treeList.forEach((v, i) => {
                if (v.checked) {
                    this.treeList.forEach((v2, i2) => {
                        if (
                            v.parentId
                                .toString()
                                .indexOf(v2.parentId.toString()) >= 0
                        ) {
                            v2.show = true;
                            if (v.parentId.includes(v2.id)) {
                                v2.showChild = true;
                                v2.open = true;
                            }
                        }
                    });
                }
            });
        },
        // 点击
        _treeItemTap(item, index) {
            if (item.lastRank === true) {
                //点击最后一级时触发事件
                this.treeList[index].checked = !this.treeList[index].checked;
                return;
            }
            let list = this.treeList;
            let id = item.id;
            item.showChild = !item.showChild;
            item.open = item.showChild ? true : !item.open;
            list.forEach((childItem, i) => {
                if (item.showChild === false) {
                    //隐藏所有子级
                    if (!childItem.parentId.includes(id)) {
                        return;
                    }
                    if (!this.foldAll) {
                        if (childItem.lastRank !== true && !childItem.open) {
                            childItem.showChild = false;
                        }
                        // 为隐藏的内容添加一个标记
                        if (childItem.show) {
                            childItem.hideArr[item.rank] = id;
                        }
                    } else {
                        if (childItem.lastRank !== true) {
                            childItem.showChild = false;
                        }
                    }
                    childItem.show = false;
                } else {
                    // 打开子集
                    if (
                        childItem.parentId[childItem.parentId.length - 1] === id
                    ) {
                        childItem.show = true;
                    }
                    // 打开被隐藏的子集
                    if (childItem.parentId.includes(id) && !this.foldAll) {
                        // console.log(childItem.hideArr)
                        if (childItem.hideArr[item.rank] === id) {
                            childItem.show = true;
                            if (childItem.open && childItem.showChild) {
                                childItem.showChild = true;
                            } else {
                                childItem.showChild = false;
                            }
                            childItem.hideArr[item.rank] = null;
                        }
                    }
                }
            });
        },
        _treeItemSelect(item, index) {
			if (item.subscribe) {
				this.$request({
				    url: '/knowledgeLabel/unsubscribe',
				    method: 'post',
				    data: {id: item.id}
				}).then(({ data }) => {
				    this.$modal.loading('已取消关注')
				    setTimeout(()=> {
				        this.$modal.closeLoading()
				    }, 1000)
				})
			} else {
				this.$request({
				    url: '/knowledgeLabel/subscribe',
				    method: 'post',
				    data: {id: item.id}
				}).then(({ data }) => {
				    this.$modal.loading('关注成功')
				    setTimeout(()=> {
				        this.$modal.closeLoading()
				    }, 1000)
				})
			}
            this.treeList[index].subscribe = !this.treeList[index].subscribe;
        },
        // 重置数据
        _reTreeList() {
            this.treeList.forEach((v, i) => {
                this.treeList[i].checked = v.orChecked;
            });
        },
        _initTree(range = this.range) {
            this.treeList = [];
            this._renderTreeList(range);
            this.$nextTick(() => {
                this._defaultSelect(range);
            });
        },
    },
    watch: {
        range(list) {
            this._initTree(list);
        },
        multiple() {
            if (this.range.length) {
                this._reTreeList();
            }
        },
        selectParent() {
            if (this.range.length) {
                this._reTreeList();
            }
        },
    },
    mounted() {
        this._initTree();
    },
};
</script>

<style scoped lang="scss">
.tki-tree-mask {
    position: fixed;
    top: 0rpx;
    right: 0rpx;
    bottom: 0rpx;
    left: 0rpx;
    z-index: 9998;
    background-color: rgba(0, 0, 0, 0.6);
    opacity: 0;
    transition: all 0.3s ease;
    visibility: hidden;
}
.tki-tree-mask.show {
    visibility: visible;
    opacity: 1;
}
.tki-tree-cnt {
    position: fixed;
    top: 0rpx;
    right: 0rpx;
    bottom: 0rpx;
    left: 0rpx;
    z-index: 9999;
    top: 160rpx;
    transition: all 0.3s ease;
    transform: translateY(100%);
}
.tki-tree-cnt.show {
    transform: translateY(0);
}
.tki-tree-bar {
    background-color: #fff;
    height: 72rpx;
    padding-left: 20rpx;
    padding-right: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    border-bottom-width: 1rpx !important;
    border-bottom-style: solid;
    border-bottom-color: #f5f5f5;
    font-size: 32rpx;
    color: #757575;
    line-height: 1;
}
.tki-tree-bar-confirm {
    color: #07bb07;
}
.tki-tree-view {
    /*position: absolute;
    top: 0rpx;
    right: 0rpx;
    bottom: 0rpx;
    left: 0rpx;
    top: 72rpx;*/
    background-color: #fff;
    padding: 30rpx;
}
.tki-tree-view-sc {
    height: 100%;
    overflow: hidden;
}
.tki-tree-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 26rpx;
    color: #757575;
    line-height: 1;
    height: 0;
    opacity: 0;
    transition: 0.2s;
    position: relative;
    overflow: hidden;
    &:hover{
        background: rgba(232, 248, 255, 1);
    }
}
.tki-tree-item.show {
    height: 80rpx;
    opacity: 1;
}
.tki-tree-item.showchild:before {
    transform: rotate(90deg);
}
.tki-tree-item.last:before {
    opacity: 0;
}
.tki-tree-icon {
    width: 26rpx;
    height: 26rpx;
    margin-right: 8rpx;
}
.tki-tree-label {
    flex: 1;
    display: flex;
    align-items: center;
    height: 100%;
    line-height: 1.2;
    font-family: Source Han Sans;
    font-size: 32rpx;
    font-weight: 500;
    color: #1C2126;
    &.tki_tree_label{
        font-family: 思源黑体;
        font-size: 14px;
        color: #4C5A67;
    }
}
.subscribe_btn{
    font-family: 思源黑体;
    font-size: 24rpx;
    border-radius: 12rpx;
    &:after{
        border: none;
    }
    &::v-deep.u-button--plain.u-button--primary{
        color: #4C5A67;
        border-color: #EAECEF;
    }
}
</style>